<style>
.pure_table_extra { width: 100%; margin-top: 5px; }
.pure_table_extra img { cursor: pointer; margin-right: 2px; }
.pure_table_extra th { height: 25px; line-height: 25px; cursor: pointer; }
.pure_table_extra td { vertical-align: middle; }
.smaller span { font-size: 11px !important; padding: 0.2em 1em !important; }
</style>

<?php
$pg = Utils::get_param('pg', 1);
$q = Utils::get_param('q', 'DESC');
$o = Utils::get_param('o', 't.order_number');
$search = json_decode(Utils::get_param('search', '{ "type": "0", "phrase": "" }'));

$opts = new stdClass();
if (isset($search->type) && isset($search->phrase)) {
  if ($search->type == 0) {
    $opts->cd = 't.is_cancel = :v0';
    $opts->cdv = array(':v0' => 0);
  } else if ($search->type == 1) {
    $opts->cd = 't.is_paid = :v1 AND t.is_cancel = :v0';
    $opts->cdv = array(':v1' => 0, ':v0' => 0);
  } else if ($search->type == 2) {
    $opts->cd = 't.is_paid = :v1 AND ship_date = :v2 AND t.is_cancel = :v0';
    $opts->cdv = array(':v1' => 1, ':v2' => '0000-00-00', ':v0' => 0);
  } else if ($search->type == 3) {
    $opts->cd = 't.ship_date >= :v1 AND t.ship_date != :v2 AND t.is_cancel = :v0';
    $opts->cdv = array(':v1' => date('Y-m-d', time() - (86400 * 10)), ':v2' => '0000-00-00', ':v0' => 0);
  } else if ($search->type == 4) {
    $opts->cd = 't.ship_date < :v1 AND t.ship_date != :v2 AND t.is_cancel = :v0';
    $opts->cdv = array(':v1' => date('Y-m-d', time() - (86400 * 10)), ':v2' => '0000-00-00', ':v0' => 0);
  } else if ($search->type == 5) {
    $opts->cd = 't.is_cancel = :v0';
    $opts->cdv = array(':v0' => 1);
  }
  
  $opts->cd .=  ' AND (t.order_number LIKE :v3 OR t.first_name LIKE :v3 OR t.last_name LIKE :v3 OR t.phone LIKE :v3 OR t.email LIKE :v3)';
  $opts->cdv[":v3"] = "%$search->phrase%";
}
$data = $orm->get('pb_ecom_order', $o, $q, $pg, SIZE, $opts);
?>

<div class="pure-form">
  <input id="find_name" type="text" style="width: 250px;" placeholder="{Search}" onkeypress="if(event.which == 13) find();">
  <select id="find_type">
    <option value="0">All</option>
    <option value="1">Unpaid</option>
    <option value="2">Paid & Unshipped</option>
    <option value="3">Shipped in last 10 days</option>
    <option value="4">Shipped after 10 days</option>
    <option value="5">Deleted</option>
  </select>
  <button type="submit" class="pure-button pure-button-primary" onclick="find();">Go</button>
</div>
<table class="pure-table pure_table_extra ui-corner-all" cellpadding=0 cellspacing=0>
  <thead>
    <tr>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('order_number');">Order No.</th>
      <th class="ui-widget-header" style="width: 60px;" onclick="return set_order('is_paid');">Paid</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('ship_date');">Shipping</th>
      <th class="ui-widget-header" style="width: 160px;" onclick="return set_order('comment');">Comment</th>
      <th class="ui-widget-header" style="width: 60px;" onclick="return set_order('total');">Total</th>
      <th class="ui-widget-header" style="width: 70px;" onclick="return set_order('first_name');">First Name</th>
      <th class="ui-widget-header" style="width: 70px;" onclick="return set_order('last_name');">Last Name</th>
      <th class="ui-widget-header" style="width: 60px;" onclick="return set_order('phone');">Phone</th>
      <th class="ui-widget-header" onclick="return set_order('email');">Email</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('payment_name');">Payment</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('delivery_name');">Courier</th>
      <th class="ui-widget-header" style="width: 60px;">&nbsp;</th>
    </tr>
  </thead>
  <tbody id="data_body"></tbody>
</table>
<div>&nbsp;</div>
<div id="pagination"></div>

<div id="dialog_change" class="pure-form pure-form-aligned " style="display: none;" title="Shipping Info">
  <div class="pure-control-group">
    <label>Date</label>
    <input id="date_change" type="text" class="pure-input-1-2" placeholder="{Date}" readonly="true"></input>
    <span class="ui-icon ui-icon-closethick" style="display: inline-block; cursor: pointer;" onclick="$('#date_change').val('0000-00-00');"></span>
  </div>
  
  <div class="pure-control-group">
    <label>&nbsp;</label>
     <span id="datepicker"></span>
  </div>
  
  <div class="pure-control-group">
    <label>Track ID</label>
    <input id="track_change" type="text" class="pure-input-1-2" placeholder="{Track ID}"></input>
  </div>
</div>

<div id="dialog_total" class="pure-form pure-form-aligned " style="display: none;" title="Total">
  <div class="pure-control-group">
    <label>Total</label>
    <input id="total_change" type="text" class="pure-input-1-2" placeholder="{Purchase Total}"></input>
  </div>
  
  <div class="pure-control-group">
    <label>Delivery Subtotal</label>
    <input id="subtotal_change" type="text" class="pure-input-1-2" placeholder="{Delivery Subtotal}"  readonly="true"></input>
  </div>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __search = JSON.parse('<?php echo addslashes(json_encode($search)); ?>');
  
  $(function(){
    render();
  });

  function render() {
    $('#pagination').pagination({
      items: __data.t,
      itemsOnPage: __data.s,
      currentPage: __data.p,
      cssStyle: 'compact-theme',
      onPageClick: function(pageNumber, event) {
        return Url.redirect(__redmd, __sys + '.php?i=' + __id + '&pg=' + pageNumber + '&o=' + __data.o + '&q=' + __data.q + '&search=' + Utils.encodeURI(JSON.stringify(__search)));
      }
    });
    render_data();
  };
  
  function render_data() {
    Url.insert_param('o', __data.o);
    Url.insert_param('q', __data.q);
    Url.insert_param('search', Utils.encodeURI(JSON.stringify(__search)));
    
    if (__search.type) {
      $('#find_type').val(__search.type);
    }
    if (__search.phrase) {
      $('#find_name').val(__search.phrase);
    }
    
    $('#data_body').empty();
    for (var idx in __data.d) {
      var itm = __data.d[idx];
      $('#data_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td>' + itm.order_number + '</td>' +
          '<td class="smaller">' + ((itm.is_cancel == 0) ? '<input id="paid_' + itm.id + '" onclick="set_paid(' + itm.id + ', this.checked);" type="checkbox" ' + ((itm.is_paid == 1) ? 'checked="checked"' : '' ) + '" /><label id="paid_txt_' + itm.id + '" for="paid_' + itm.id + '" style="margin-right: 0;">' + ((itm.is_paid == 1) ? 'Paid' : 'Unpaid' ) + '</label>' : ((itm.is_paid == 1) ? 'Paid' : 'Unpaid' )) + '</td>' +
          '<td>' + ((itm.is_cancel == 0) ? '<a href="#" onclick="set_ship(' + itm.id + ', event);">' + ((itm.ship_date == '0000-00-00') ? 'Unshipped' : itm.ship_date) + '</a>' :  ((itm.ship_date == '0000-00-00') ? 'Unshipped' : itm.ship_date)) + '</td>' +
          '<td title="' + itm.comment + '">' + Utils.get_short(itm.comment, 20) + '</td>' +
          '<td>' + ((itm.is_cancel == 0) ? '<a href="#" onclick="set_total(' + itm.id + ', event);">' + accounting.formatMoney(parseFloat(itm.total, 10) + parseFloat(itm.delivery_subtotal, 10), itm.curr) + '</a>' : accounting.formatMoney(parseFloat(itm.total, 10) + parseFloat(itm.delivery_subtotal, 10), itm.curr)) + '</td>' +
          '<td title="' + itm.first_name + '">' + Utils.get_short(itm.first_name, 10) + '</td>' +
          '<td title="' + itm.last_name + '">' + Utils.get_short(itm.last_name, 10) + '</td>' +
          '<td title="' + itm.phone + '">' + Utils.get_short(itm.phone, 10) + '</td>' +
          '<td>' + itm.email + '</td>' +
          '<td title="' + itm.payment_name + '">' + Utils.get_short(itm.payment_name, 10) + '</td>' +
          '<td title="' + itm.delivery_name + '">' + Utils.get_short(itm.delivery_name, 10) + '</td>' +
          '<td>' +
            '<span title="Print" style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-print" onclick="window.open(\'<?php echo URL . HOME_DIR . '__odprint.php?__sys=' . $app_data->sys->php_name . '&od='; ?>' + itm.order_number + '\');"></span>' +
            '<span title="View" style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-pencil" onclick="Url.redirect(' + __redmd + ', \'' + __sys + '.php?i=' + __id + '&__file=index_order&id=' + itm.id + '&pg=' + __data.p + '\');"></span>' +
            ((itm.is_cancel == 0 && itm.is_paid == 0) ? '<span title="Cancel" style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="cancel_obj(' + itm.id + ');"></span>' : '') +
            ((itm.is_cancel == 1) ? '<span title="Restore" style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-arrowreturnthick-1-w" onclick="restore_obj(' + itm.id + ');"></span>' : '') +
            '</td>' + 
        '</tr>'
      );
    }
    if (__data.d.length == 0) {
      $('#data_body').append('<tr class="pure-table-even"><td colspan=12>None</td></tr>');
    }
    $('#data_body input[type=checkbox]').button();
  };


  function __get_search() {
    return {
      type: $('#find_type option:selected').val(),
      phrase: $('#find_name').val()
    };
  };

  function set_ship(id, ev) {
    var obj = Utils.get_by_id(id, __data.d);

    $('#noty_inline_layout_container').remove();
    if (obj.is_paid == 0) {
      Utils.message('The order is unpaid', 'error');
      return;
    }
    
    var func = function() {
      var req = Utils.get_by_id(id, __data.d);
      req.ship_date = $('#date_change')[0].value;
      req.ship_track = $('#track_change')[0].value;
      
      Ajax.request(
        __requrl + 'submit_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          render_data();
          $('#dialog_change').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_change').dialog({
      width: 500,
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });
    
    $('#datepicker').datepicker({
      defaultDate: (obj.ship_date == '0000-00-00') ? new Date() : new Date(obj.ship_date),
      onSelect: function(dateText, inst) {
        $('#date_change').val(inst.currentYear + '-' + (inst.currentMonth + 1) + '-' + inst.currentDay);
      }
    });
    $('.ui-datepicker-inline')[0].style.display = 'inline-block';
    

    var d = new Date();
    $('#date_change').val(obj.ship_date == '0000-00-00' ? d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() : obj.ship_date);
    $('#track_change').val(obj.ship_track);
  };

  function set_total(id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __data.d);
      req.total = $('#total_change')[0].value - req.delivery_subtotal;
      
      Ajax.request(
        __requrl + 'submit_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          render_data();
          $('#dialog_total').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_total').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });

    var obj = Utils.get_by_id(id, __data.d);

    $('#total_change')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };

    $('#total_change').val((parseFloat(obj.total, 10) + parseFloat(obj.delivery_subtotal, 10)).toFixed(2));
    $('#subtotal_change').val(obj.delivery_subtotal);
    
  };
  
  function cancel_obj(id) {
    var req = Utils.get_by_id(id, __data.d);
    req.__pg = __data.p;
    req.is_cancel = 1;
    Ajax.request(
      __requrl + 'cancel',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        render_data();
      },
      { confirm: 1 }
    );
  };

  function restore_obj(id) {
    var req = Utils.get_by_id(id, __data.d);
    req.__pg = __data.p;
    req.is_cancel = 0;
    Ajax.request(
      __requrl + 'restore',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        render_data();
      },
      { confirm: 1 }
    );
  };

  function set_paid(id, paid) {
    var req = Utils.get_by_id(id, __data.d);

    $('#noty_inline_layout_container').remove();
    if (req.ship_date != '0000-00-00') {
      Utils.message('The order is shipped', 'error');
      if (paid) {
        $('#paid_' + id)[0].checked = false;
        $('#paid_txt_' + id).empty();
        $('#paid_txt_' + id).append('<span class="ui-button-text">Unpaid</span>');
        $('#paid_txt_' + id).removeClass('ui-state-active');
      } else {
        $('#paid_' + id)[0].checked = true;
        $('#paid_txt_' + id).empty();
        $('#paid_txt_' + id).append('<span class="ui-button-text">Paid</span>');
        $('#paid_txt_' + id).addClass('ui-state-active');
      }
      return;
    }
    
    if (paid) {
      $('#paid_' + id)[0].checked = true;
      $('#paid_txt_' + id).empty();
      $('#paid_txt_' + id).append('<span class="ui-button-text">Paid</span>');
      $('#paid_txt_' + id).addClass('ui-state-active');
    } else {
      $('#paid_' + id)[0].checked = false;
      $('#paid_txt_' + id).empty();
      $('#paid_txt_' + id).append('<span class="ui-button-text">Unpaid</span>');
      $('#paid_txt_' + id).removeClass('ui-state-active');
    }
    
    req.is_paid = paid ? 1 : 0;
    render_data();
    Ajax.request(
      __requrl + 'pay',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
      },
      { silent: 1 }
    );
  };

  function set_order(o) {
    var req = {
      q: (__data.q) == 'ASC' ? 'DESC' : 'ASC',
      o: o,
      pg: __data.p,
      search: __search
    };
    Ajax.request(
      __requrl + 'get_objs',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      null
    );
  };

  function find() {
    __search = __get_search();
    
    var req = {
      q: __data.q,
      o: __data.o,
      pg: __data.p,
      search: __search
    };
    Ajax.request(
      __requrl + 'get_objs',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      null
    );
  };
  /*]]>*/
</script>